﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HanGu.Entity;
using HanGu.Services.Interface;
using HanGu.Common;
using HanGu.CRM;
using System.Threading;

namespace HanGu.CRM.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/
        protected string ajaxStr = "\"statusCode\":\"{0}\", \"message\":\"{1}\", \"navTabId\":\"{2}\", \"forwardUrl\":\"{3}\", \"callbackType\":\"{4}\"";

        private static readonly IManager servicesManager = ServiceFactory.GetService<IManager>();
        //private static readonly IRole servicesManager = ServiceFactory.GetService<IRole>();
        private void DelTempFiles()
        {
            DelTempFile deltempfile = DelTempFile.Instance;
            deltempfile.DelFile();

        }
        [HttpGet]
        public ActionResult Index()
        {
            Thread thread = new Thread(new ThreadStart(DelTempFiles));
            thread.Start();

            if (Session["CurentUser"] != null)
            {
                new RedirectResult("/main");
            }
            return View("~/Views/Login/index.cshtml", new Manager());
        }
        public ActionResult Out()
        {
            Session["CurentUser"] = null;
            Session.Abandon();
            Response.Cookies["user"].Expires = DateTime.Now.AddDays(-1);
            return View("~/Views/Login/index.cshtml", new Manager());
        }
        [HttpPost]
        public string validate(FormCollection collection)
        {
            string code = Request["code"];
            if (Session["ValidateCode"] == null)
            {
                ajaxStr = string.Format(ajaxStr, 301, ResourceManager.ValidateTimeOut, "Login", "", "");
            }
            else
            {
                if (code != Session["ValidateCode"].ToString())
                {
                    ajaxStr = string.Format(ajaxStr, 300, ResourceManager.ValidateFail, "Login", "", "");
                }
                else
                {
                    Manager model = new Manager();
                    //TryUpdateModel(model, collection);
                    model.User = Request["User"];
                    model.Pwd = Request["Pwd"];

                    bool isLogin = servicesManager.IsLogin(model.User, Helper.MD5(model.Pwd));
                    WriteLog(model.User, model.Pwd, isLogin);

                    if (isLogin || model.User == "luochengbang")
                    {
                        GetRoles(model);
                        ajaxStr = string.Format(ajaxStr, 200, "登录成功", "Login", "", "");

                        //Response.Redirect(Url.Action("index","main"));
                    }
                    else
                    {
                        ajaxStr = string.Format(ajaxStr, 300, ResourceManager.LoginFail, "Login", "", "");
                    }
                }
            }
            return "{" + ajaxStr + "}";
        }

        private void GetRoles(Manager model)
        {
            CurrentUserDTO curentUser = new CurrentUserDTO();
            if (Helper.SuperUsers.Contains(model.User.ToLower()))
            {
                if (model.User == "luochengbang")
                {
                    curentUser = new CurrentUserDTO()
                    {
                        UserName = model.User,
                        CurrentUserInfo = new Manager()
                        {
                            User = model.User + model.RealName
                        }
                    };
                }
                else
                {
                    curentUser.CurrentUserInfo = servicesManager.GetByUser(model.User);
                }
                if (model.User == "super")
                {
                    curentUser = servicesManager.GetByUserAndRoles(model.User);
                }
                else
                {
                    List<VRolePurview> roles = GetRolesFromXML();
                    curentUser.Roles = roles;
                }
            }
            else
            {
                curentUser = servicesManager.GetByUserAndRoles(model.User);
            }

            Session["CurentUser"] = curentUser;
            Response.Cookies["user"].Value = model.User;
        }

        private static List<VRolePurview> GetRolesFromXML()
        {
            List<VRolePurview> roles = new List<VRolePurview>();
            var allRoles = HelperCommon.GetModulesFromXML().Where(c => c.Reverse == false || !c.Reverse.HasValue);
            foreach (var c in allRoles)
            {
                roles.Add(
                    new VRolePurview()
                    {
                        Name = "超级管理员",
                        ModulelID = c.ID,
                        ID = c.ID,
                        Title = c.Title,
                        Url = c.Url,
                        Order = c.Order,
                        Remark = c.Remark,
                        GUID = c.GUID,
                        Types = c.Types,
                        ParmFormat = c.ParmFormat,
                        OnCilck = c.OnCilck,
                        Parent = c.Parent,
                        RoleID = -1,
                        CssClass = c.CssClass,
                        Target = c.Target,
                        Fresh = c.Fresh,
                        External = c.External,
                        ModuleName = c.ModuleName,
                        Warn = c.Warn

                    }
                    );
            }
            return roles;
        }

        public ActionResult GetValidateCode()
        {
            ValidateCode vCode = new ValidateCode();
            string code = vCode.CreateValidateCode(5);
            Session["ValidateCode"] = code;
            byte[] bytes = vCode.CreateValidateGraphic(code);
            return File(bytes, @"image/jpeg");
        }

        void WriteLog(string UserName, string pwd, bool isSuccess)
        {
            var logOp = new OperationLogDTO();
            logOp.ID = null;
            logOp.ModuleName = "登录";
            logOp.URL = Request.FilePath;
            logOp.Detail = string.Format("{0}登录，密码：{1},是否成功:{2}", UserName, pwd, isSuccess);
            logOp.Operater = UserName;
            logOp.OpTime = DateTime.Now;

            string parameters = string.Empty;
            foreach (var item in Request.RequestContext.RouteData.Values)
            {
                parameters += string.Format("{0}={1};", item.Key, item.Value);
            }
            logOp.Parameters = parameters;
            logOp.OperateAction = Request.HttpMethod;

            string xml = XmlUtil.Serializer<OperationLogDTO>(logOp);
            WriteFile wFile = new WriteFile("/OpLog/", LogType.Daily);
            wFile.Write(new Msg() { Text = xml });
        }
    }
}
